package app.sevenc.lib_framework.utils

import android.os.Handler
import android.os.Looper
import androidx.annotation.MainThread
import androidx.lifecycle.LiveData

/**
 * LiveData实现全局定时器
 * 一个全局计数器，Activity销毁时，计时器停止，不会导致内存泄露，Activity激活时，计时器开始，自动获取最新的计时。
 *
 * 开启计时器 TimerGlobalLiveData.get().startTimer()
 * 停止计时器 TimerGlobalLiveData.get().cancelTimer()
 * 全局监听
 * TimerGlobalLiveData.get().observe(this) {
 * Log.i(TAG, "GlobalTimer value: ==  $it")
 * }
 *
 * @author Seven-C
 * @date 2021/8/26
 */
class TimerGlobalLiveData : LiveData<Int>() {

    private val handler: Handler = Handler(Looper.getMainLooper())

    private val timerRunnable = object : Runnable {
        override fun run() {
            postValue(count++)
            if (count >= maxCount) {
                cancelTimer()
            } else {
                handler.postDelayed(this, 1000)
            }
        }
    }

    fun startTimer() {
        count = 0
        handler.postDelayed(timerRunnable, 1000)
    }

    fun cancelTimer() {
        handler.removeCallbacks(timerRunnable)
    }

    companion object {
        private lateinit var sInstance: TimerGlobalLiveData

        private var count = 0

        private val maxCount = 60

        @MainThread
        fun get(): TimerGlobalLiveData {
            sInstance = if (::sInstance.isInitialized) sInstance else TimerGlobalLiveData()
            return sInstance
        }
    }

}